import React, { useState, useCallback } from 'react';
import {
  Box,
  Button,
  Paper,
  Typography,
  IconButton,
  CircularProgress,
  Alert,
  Snackbar,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  ListItemButton,
  Collapse,
  Checkbox,
  FormControlLabel,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions
} from '@mui/material';
import {
  ExpandMore,
  ChevronRight,
  Folder,
  Warning,
  Launch,
  Refresh,
  FindInPage,
  SaveAlt
} from '@mui/icons-material';
const { ipcRenderer } = window.require('electron');

interface DirectoryNode {
  path: string;
  name: string;
  children: DirectoryNode[];
  hasImages: boolean;
  hasAtlas: boolean;
  shouldCheck: boolean;
}

function App() {
  const [directoryTree, setDirectoryTree] = useState<DirectoryNode | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [showOnlyIssues, setShowOnlyIssues] = useState(false);
  const [currentPath, setCurrentPath] = useState<string | null>(null);
  const [issueCount, setIssueCount] = useState(0);
  const [checkResult, setCheckResult] = useState<{
    directories: Array<{
      directory: string;
      hasPacFnt: boolean;
      hasPacPlist: boolean;
      details: {
        hasPac: boolean;
        hasFnt: boolean;
        hasPlist: boolean;
      };
    }>;
    summary: {
      totalDirs: number;
      matchingDirs: number;
    };
  } | null>(null);
  const [showCheckDialog, setShowCheckDialog] = useState(false);
  const [prefabUuids, setPrefabUuids] = useState<string[]>([]);
  const [prefabScanResults, setPrefabScanResults] = useState<any>(null);
  const [showPrefabDialog, setShowPrefabDialog] = useState(false);

  // 统计异常目录数量
  const countIssueDirectories = useCallback((node: DirectoryNode): number => {
    let count = 0;
    if (node.shouldCheck && node.hasImages && !node.hasAtlas) {
      count++;
    }
    if (Array.isArray(node.children)) {
      count += node.children.reduce((sum, child) => sum + countIssueDirectories(child), 0);
    }
    return count;
  }, []);

  // 扫描目录
  const scanDirectory = useCallback(async (path: string) => {
    try {
      console.log('开始扫描目录');
      const tree = await ipcRenderer.invoke('scan-directory', path);
      console.log('扫描结果:', tree);
      if (!tree) {
        throw new Error('目录扫描结果为空');
      }
      setDirectoryTree(tree);
      setExpanded(new Set([tree.path]));
      setIssueCount(countIssueDirectories(tree));
    } catch (err) {
      console.error('扫描出错:', err);
      setError(err instanceof Error ? err.message : '扫描目录时发生错误');
      setDirectoryTree(null);
      setExpanded(new Set());
      setIssueCount(0);
    }
  }, [countIssueDirectories]);

  const handleSelectFolder = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      setDirectoryTree(null);
      const folderPath = await ipcRenderer.invoke('select-folder');
      console.log('选择的文件夹:', folderPath);
      
      if (folderPath) {
        setCurrentPath(folderPath);
        await scanDirectory(folderPath);
      } else {
        console.log('未选择文件夹');
      }
    } catch (err) {
      console.error('错误:', err);
      setError(err instanceof Error ? err.message : '扫描目录时发生错误');
      setDirectoryTree(null);
      setExpanded(new Set());
      setIssueCount(0);
    } finally {
      setLoading(false);
    }
  }, [scanDirectory]);

  const handleRefresh = useCallback(async () => {
    if (!currentPath) {
      setError('请先选择一个目录');
      return;
    }
    setLoading(true);
    try {
      await scanDirectory(currentPath);
    } finally {
      setLoading(false);
    }
  }, [currentPath, scanDirectory]);

  const handleCheckCombinations = useCallback(async () => {
    if (!currentPath) {
      setError('请先选择一个目录');
      return;
    }
    
    try {
      setLoading(true);
      const result = await ipcRenderer.invoke('check-file-combinations', currentPath);
      setCheckResult(result);
      setShowCheckDialog(true);
    } catch (err) {
      console.error('检查文件组合时出错:', err);
      setError(err instanceof Error ? err.message : '检查文件组合时发生错误');
    } finally {
      setLoading(false);
    }
  }, [currentPath]);

  const handleCloseCheckDialog = useCallback(() => {
    setShowCheckDialog(false);
  }, []);

  const toggleNode = useCallback((path: string) => {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  }, []);

  const openFolder = useCallback(async (path: string) => {
    try {
      console.log('打开文件夹:', path);
      await ipcRenderer.invoke('open-path', path);
    } catch (err) {
      console.error('打开文件夹时出错:', err);
      setError(err instanceof Error ? err.message : '打开目录时发生错误');
    }
  }, []);

  const handleCloseError = useCallback(() => {
    setError(null);
  }, []);

  // 检查目录及其子目录是否有问题
  const hasIssuesInTree = useCallback((node: DirectoryNode): boolean => {
    // 检查当前目录是否需要检查
    const hasIssue = node.shouldCheck;
    if (hasIssue) return true;
    
    if (Array.isArray(node.children) && node.children.length > 0) {
      return node.children.some(child => hasIssuesInTree(child));
    }
    
    return false;
  }, []);

  const renderTree = useCallback((node: DirectoryNode, level: number = 0) => {
    if (!node || !node.path || !node.name) {
      return null;
    }

    // 检查当前目录是否需要检查
    const hasIssue = node.shouldCheck;
    const hasChildIssues = hasIssuesInTree(node);

    // 只在启用过滤时进行过滤
    if (showOnlyIssues && !hasIssue && !hasChildIssues) {
      return null;
    }

    const isExpanded = expanded.has(node.path);
    const hasChildren = Array.isArray(node.children) && node.children.length > 0;

    // 是否应该显示警告
    const shouldShowWarning = hasIssue;

    return (
      <React.Fragment key={node.path}>
        <ListItem
          sx={{
            pl: level * 2,
            borderRadius: 1,
            '&:hover': {
              backgroundColor: 'rgba(0, 0, 0, 0.04)'
            },
            ...(shouldShowWarning && {
              backgroundColor: 'rgba(255, 152, 0, 0.05)'
            })
          }}
          disablePadding
        >
          <ListItemButton onClick={() => hasChildren && toggleNode(node.path)}>
            <ListItemIcon sx={{ minWidth: 36 }}>
              {hasChildren ? (
                isExpanded ? <ExpandMore /> : <ChevronRight />
              ) : (
                <Folder fontSize="small" color={shouldShowWarning ? "warning" : "action"} />
              )}
            </ListItemIcon>
            <ListItemText 
              primary={node.name}
              primaryTypographyProps={{ 
                variant: 'body2',
                color: shouldShowWarning ? 'warning.main' : 'inherit'
              }}
            />
            {shouldShowWarning && (
              <Warning color="warning" fontSize="small" sx={{ ml: 1 }} />
            )}
            <IconButton
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                openFolder(node.path);
              }}
              sx={{ ml: 1 }}
            >
              <Launch fontSize="small" />
            </IconButton>
          </ListItemButton>
        </ListItem>
        {hasChildren && (
          <Collapse in={isExpanded} timeout="auto" unmountOnExit>
            <List disablePadding>
              {node.children.map(child => renderTree(child, level + 1))}
            </List>
          </Collapse>
        )}
      </React.Fragment>
    );
  }, [expanded, openFolder, toggleNode, showOnlyIssues, hasIssuesInTree]);

  const handleScanPrefab = useCallback(async () => {
    if (!currentPath) {
      setError('请先选择一个目录');
      return;
    }
    
    try {
      setLoading(true);
      const result = await ipcRenderer.invoke('scan-prefab-files', currentPath);
      setPrefabUuids(result.uuids);
      setPrefabScanResults(result.scanResults);
      setShowPrefabDialog(true);
    } catch (err) {
      console.error('扫描prefab文件时出错:', err);
      setError(err instanceof Error ? err.message : '扫描prefab文件时发生错误');
    } finally {
      setLoading(false);
    }
  }, [currentPath]);

  const handleExportPrefabResults = useCallback(async () => {
    if (!prefabScanResults) return;
    
    try {
      setLoading(true);
      const result = await ipcRenderer.invoke('save-prefab-scan-results', prefabScanResults);
      if (result.success) {
        // 成功保存，显示路径信息
        alert(`扫描结果已保存到: ${result.filePath}`);
      } else if (result.message) {
        // 用户取消了保存或其他情况
        console.log(result.message);
      }
    } catch (err) {
      console.error('导出扫描结果时出错:', err);
      setError(err instanceof Error ? err.message : '导出扫描结果时发生错误');
    } finally {
      setLoading(false);
    }
  }, [prefabScanResults]);

  return (
    <Box sx={{ p: 3 }}>
      <Paper sx={{ p: 2, mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
          <Button
            variant="contained"
            onClick={handleSelectFolder}
            disabled={loading}
            title="选择待扫描的文件夹"
          >
            选择文件夹
          </Button>
          <Button
            variant="outlined"
            onClick={handleRefresh}
            disabled={loading || !currentPath}
            startIcon={<Refresh />}
            title="刷新目录扫描结果"
          >
            刷新
          </Button>
          <Button
            variant="outlined"
            onClick={handleCheckCombinations}
            disabled={loading || !currentPath}
            startIcon={<FindInPage />}
            title="检查同时存在.pac和.plist的文件组合"
          >
            检查文件组合
          </Button>
          <Button
            variant="outlined"
            onClick={handleScanPrefab}
            disabled={loading || !currentPath}
            startIcon={<FindInPage />}
            title="扫描同时存在粒子和plist图集的Prefab"
          >
            扫描Prefab
          </Button>
          {loading && <CircularProgress size={24} />}
          <FormControlLabel
            control={
              <Checkbox
                checked={showOnlyIssues}
                onChange={(e) => setShowOnlyIssues(e.target.checked)}
                disabled={loading || !directoryTree}
              />
            }
            label="只显示异常目录"
          />
          {directoryTree && (
            <Typography color="warning.main" sx={{ ml: 'auto' }}>
              发现 {issueCount} 个异常目录
            </Typography>
          )}
        </Box>
        
        {directoryTree && (
          <Box 
            sx={{ 
              mt: 2,
              border: '1px solid #e0e0e0',
              borderRadius: 1,
              maxHeight: 'calc(100vh - 200px)',
              overflow: 'auto'
            }}
          >
            <List>
              {renderTree(directoryTree)}
            </List>
          </Box>
        )}
      </Paper>

      <Dialog 
        open={showCheckDialog} 
        onClose={handleCloseCheckDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>文件组合检查结果</DialogTitle>
        <DialogContent>
          {checkResult && (
            <Box sx={{ mt: 1 }}>
              <Typography variant="h6" gutterBottom>
                扫描摘要
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                共扫描 {checkResult.summary.totalDirs} 个目录，
                找到 {checkResult.summary.matchingDirs} 个匹配目录
              </Typography>

              <Typography variant="h6" sx={{ mt: 3, mb: 2 }}>
                匹配目录列表
              </Typography>
              
              {checkResult.directories.length === 0 ? (
                <Typography variant="body2" color="text.secondary">
                  未找到同时包含 .pac 和 .plist 的目录
                </Typography>
              ) : (
                <List sx={{ 
                  width: '100%', 
                  bgcolor: 'background.paper',
                  border: '1px solid',
                  borderColor: 'divider',
                  borderRadius: 1,
                  maxHeight: '400px',
                  overflow: 'auto'
                }}>
                  {checkResult.directories.map((result, index) => (
                    <ListItem 
                      key={result.directory}
                      divider={index < checkResult.directories.length - 1}
                      sx={{ flexDirection: 'column', alignItems: 'flex-start' }}
                    >
                      <Box sx={{ width: '100%', display: 'flex', alignItems: 'center', mb: 1 }}>
                        <Typography 
                          variant="body2" 
                          component="div" 
                          sx={{ 
                            flexGrow: 1,
                            fontFamily: 'monospace',
                            fontSize: '0.9rem'
                          }}
                        >
                          {result.directory}
                        </Typography>
                        <IconButton
                          size="small"
                          onClick={() => openFolder(result.directory)}
                          sx={{ ml: 1 }}
                        >
                          <Launch fontSize="small" />
                        </IconButton>
                      </Box>
                      <Box sx={{ display: 'flex', gap: 2 }}>
                        {result.hasPacFnt && (
                          <Typography 
                            variant="body2" 
                            color="success.main"
                            sx={{ display: 'flex', alignItems: 'center' }}
                          >
                            ✓ .pac + .fnt
                          </Typography>
                        )}
                        {result.hasPacPlist && (
                          <Typography 
                            variant="body2" 
                            color="success.main"
                            sx={{ display: 'flex', alignItems: 'center' }}
                          >
                            ✓ .pac + .plist
                          </Typography>
                        )}
                      </Box>
                    </ListItem>
                  ))}
                </List>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCheckDialog}>关闭</Button>
        </DialogActions>
      </Dialog>

      <Dialog
        open={showPrefabDialog}
        onClose={() => setShowPrefabDialog(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>Prefab Atlas UUID列表</DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <Typography variant="body1" gutterBottom>
              共找到 {prefabUuids.length} 个UUID
            </Typography>
            {prefabScanResults && prefabScanResults.files && (
              <Typography variant="body2" gutterBottom>
                包含粒子系统的Prefab文件: {prefabScanResults.files.length} 个
              </Typography>
            )}
            <List sx={{ 
              maxHeight: '400px',
              overflow: 'auto',
              bgcolor: 'background.paper',
              border: '1px solid',
              borderColor: 'divider',
              borderRadius: 1
            }}>
              {prefabUuids.map((uuid, index) => (
                <ListItem 
                  key={uuid}
                  divider={index < prefabUuids.length - 1}
                  sx={{ fontFamily: 'monospace', fontSize: '0.8rem' }}
                >
                  {uuid}
                </ListItem>
              ))}
            </List>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button 
            variant="contained" 
            color="primary" 
            onClick={handleExportPrefabResults} 
            disabled={!prefabScanResults || loading}
            startIcon={<SaveAlt />}
          >
            导出扫描结果
          </Button>
          <Button onClick={() => setShowPrefabDialog(false)}>关闭</Button>
        </DialogActions>
      </Dialog>

      <Snackbar 
        open={error !== null} 
        autoHideDuration={6000} 
        onClose={handleCloseError}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseError} 
          severity="error" 
          sx={{ width: '100%' }}
        >
          {error}
        </Alert>
      </Snackbar>
    </Box>
  );
}

export default App;